from OpenSSL import crypto
from twisted.internet import ssl

# 创建一个私钥
pkey = crypto.PKey()
pkey.generate_key(crypto.TYPE_RSA, 2048)

# 创建一个证书请求
csr = crypto.X509Req()
csr.get_subject().CN = 'your_domain_name'  # 替换成你的域名
csr.set_pubkey(pkey)
csr.sign(pkey, 'sha256')

# 写入私钥和证书请求到同一个PEM文件
cert_file = open('server.pem', 'wt')
cert_file.write(crypto.dump_privatekey(crypto.FILETYPE_PEM, pkey))
cert_file.write(crypto.dump_certificate_request(crypto.FILETYPE_PEM, csr))
cert_file.close()

# 使用ssl模块创建TLS服务器
from twisted.internet import reactor
from twisted.web.server import Site
from twisted.web.static import File

# 加载证书和私钥
context = ssl.DefaultOpenSSLContextFactory('server.pem', lambda: pkey)

# 定义网站目录
web_dir = File('/path/to/your/web/content')

# 启动HTTPS服务器
factory = Site(web_dir)
factory.protocol = lambda: reactor.wrapProtocol(factory.protocol, context)
reactor.listenSSL(443, factory, context)
reactor.run()  # 开始监听12